Blog Summary 发表于 2017-07-17 Web常用1234567891011121314151617181920212223242526req.body.xxx //获取页面body里的参数res.render('xx') //将页面渲染到xx里req.query.xxx; //获取页面URL中带的参数res.render('detail',{ blogs: result[0] }); //渲染页面并传入参数,通过在数据库中查询得到的result是数组,不用result[0]传入,将显示Object对象 <%= blog.content %> //在ejs中接收数据<% blogs.forEach(blog => { %> <li> <a href="/detail?blog_id=<%= blog.id %>"><%= blog.title %></a> </li> <% }) %> </ul> //这种情况是将result直接传入,由于blogs是数组,所以用遍历forEach //其中a标签中设置了带blog的id跳转module.exports = { insertData:insertData, selectData:selectData, selectDataContent:selectDataContent }; //同一个JS中暴露多个函数,var selectData = require('../tools/db').selectData;var selectDataContent = require('../tools/db').selectDataContent; //调用暴露的多个函数 Cookie设置cookie1234567891011121314var crypto = require('crypto');var md5 = crypto.createHash('md5');exports.authorizations = [];exports.cookies = function(req, res, username){ md5 = crypto.createHash('md5'); md5.update(username + (new Date()).toString()); var auth = md5.digest('hex'); console.log(auth); exports.authorizations.push({username: username, auth: auth}); res.cookie('username', username, {maxAge: 1 * 30 * 1000}); res.cookie('auth', auth, {maxAge: 1 * 30 * 1000});} 调用md5.digest生成一组特殊的数值 exports.authorizations.push将页面传来的username加入到数组里 res.cookie设置username和特殊值存在的时间 将username存入cookie123456789router.post('/', function(req, res, next) { var username = req.body.username; console.log(username); if(username === ""){ res.render('loginFail'); } auth.cookies(req, res, username); res.render('new');}); 设置路由12345678910var auth = require('../tools/cookie');router.get('/new', function(req, res, next) { if((auth.authorizations.some(e => e.username === req.cookies.username)) && (auth.authorizations.some(e => e.auth === req.cookies.auth))){ console.log(auth.authorizations); res.render('new'); } else { res.render("login"); }}); 当客户端发送new请求,进入这个路由 检查req.cookies.username和cookie里存的值是否相同